﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SampleImageGenerator.Core;
using SampleImageGenerator.Core.Events;

namespace SampleImageGenerator.Controls
{
	internal partial class ImageDisplay : EngineListenerControl
	{
		public ImageDisplay()
		{
			InitializeComponent();
		}

		protected override void AttachEventHandlers(IEngine engine)
		{
			engine.ImageGenerated += ImageGeneratedInvoker;
		}

		protected override void DetachEventHandlers(IEngine engine)
		{
			engine.ImageGenerated -= ImageGeneratedInvoker;
		}

		protected override void UpdateState(IEngine engine)
		{
		}

		void ImageGeneratedInvoker(object sender, ImageGeneratedEventArgs e)
		{
			if (this.InvokeRequired)
			{
				Object[] args = new Object[] { sender, e };
				EventHandler<ImageGeneratedEventArgs> handler = ImageGeneratedHandler;
				this.Invoke(handler, args);
			}
			else
			{
				ImageGeneratedHandler(sender, e);
			}
		}

		private void ImageGeneratedHandler(object sender, ImageGeneratedEventArgs e)
		{
			if (Engine != null)
			{
				Image oldImage = pictureBoxImage.Image;

				Image newImage = e.GetImage();
				this.pictureBoxImage.Image = newImage;

				if (oldImage != null)
				{
					oldImage.Dispose();
				}
			}
		}
	}
}
